'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import diff from 'microdiff';
import type {
  IConfigSite,
  IDifference,
  IUpdateSiteConfigBody,
} from '@/interfaces';
import type { TBody } from '@/types';
import { updateSiteConfig } from '@/services/api';
import useToast from '@/hooks/useToast';
import { ConfigAdminContext } from '@/contexts/admin/config';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateConfigSite({
  details,
}: {
  details: IConfigSite;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    helpLink?: string;
    feedbackLink?: string;
    reportLink?: string;
    githubLink?: string;
    mpImageLink?: string;
    disableRegistration?: boolean;
  }>({
    helpLink: '',
    feedbackLink: '',
    reportLink: '',
    githubLink: '',
    mpImageLink: '',
    disableRegistration: false,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();
  const context = useContext(ConfigAdminContext);

  const updateSiteConfigMutation = useMutation(
    async (variables: TBody<IUpdateSiteConfigBody>) => {
      await updateSiteConfig(variables);
      await queryClient.invalidateQueries([
        '/configs',
        `/${context.updateItem?.id}`,
      ]);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        helpLink: details.helpLink || '',
        feedbackLink: details.feedbackLink || '',
        reportLink: details.reportLink || '',
        githubLink: details.githubLink || '',
        mpImageLink: details.mpImageLink || '',
        disableRegistration: details.disableRegistration || false,
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          helpLink: details.helpLink || '',
          feedbackLink: details.feedbackLink || '',
          reportLink: details.reportLink || '',
          githubLink: details.githubLink || '',
          mpImageLink: details.mpImageLink || '',
          disableRegistration: details.disableRegistration || false,
        },
        {
          helpLink: form.helpLink,
          feedbackLink: form.feedbackLink,
          reportLink: form.reportLink,
          githubLink: form.githubLink,
          mpImageLink: form.mpImageLink,
          disableRegistration: form.disableRegistration,
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'disableRegistration') {
      setForm({ ...form, disableRegistration: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateSiteConfigMutation.mutateAsync({
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateSiteConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">帮助链接</label>
            <input
              type="text"
              className="form-control"
              name="helpLink"
              value={form.helpLink}
              onChange={onChangeForm}
              aria-describedby="helpLink"
              placeholder="请输入帮助链接"
            />
          </div>

          <div>
            <label className="form-label">反馈链接</label>
            <input
              type="text"
              className="form-control"
              name="feedbackLink"
              value={form.feedbackLink}
              onChange={onChangeForm}
              aria-describedby="feedbackLink"
              placeholder="请输入反馈链接"
            />
          </div>

          <div>
            <label className="form-label">举报链接</label>
            <input
              type="text"
              className="form-control"
              name="reportLink"
              value={form.reportLink}
              onChange={onChangeForm}
              aria-describedby="reportLink"
              placeholder="请输入举报链接"
            />
          </div>

          <div>
            <label className="form-label">Github 链接</label>
            <input
              type="text"
              className="form-control"
              name="githubLink"
              value={form.githubLink}
              onChange={onChangeForm}
              aria-describedby="githubLink"
              placeholder="请输入 Github 链接"
            />
          </div>

          <div>
            <label className="form-label">小程序图片链接</label>
            <input
              type="text"
              className="form-control"
              name="mpImageLink"
              value={form.mpImageLink}
              onChange={onChangeForm}
              aria-describedby="mpImageLink"
              placeholder="请输入小程序图片链接"
            />
          </div>

          <div>
            <label className="form-label">关闭注册</label>
            <select
              name="disableRegistration"
              value={form.disableRegistration ? 'true' : 'false'}
              onChange={onChangeForm}
              className="form-select"
              aria-label="disableRegistration"
              placeholder="请选择是否关闭注册"
            >
              <option value="true">true</option>
              <option value="false">false</option>
            </select>
          </div>

          <button
            type="submit"
            disabled={updateSiteConfigMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateSiteConfigMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
